package com.xzzz.irda.auth.core.filter.impl;

import com.xzzz.irda.auth.core.constants.AuthConstant;
import com.xzzz.irda.auth.core.request.BodyReaderHttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 包装request, 提供多次读取请求体的机会
 *
 * @author wangyf
 *
 */
@Slf4j
@Order(AuthConstant.Filter.REQUEST_WRAPPER_FILTER)
public class RequestWrapperFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //post请求为json格式才封装包装类，因为后续记录参数日志会读取请求参数的流，流只能读一次所以要用包装类
        //这样是为了过滤post请求上传文件时记录参数日志报错
        if (request.getContentType() != null && request.getContentType().contains("application/json")) {
            ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
            filterChain.doFilter(requestWrapper, response);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
